<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>xv6 实验十 mmap | kiloGrand</title><meta name="keywords" content="xv6"><meta name="author" content="kiloGrand"><meta name="copyright" content="kiloGrand"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;schedule.html https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;labs&#x2F;mmap.html  本次实验只需实现简化版的 mmap和munmap  保证 addr 和 offset 都为 0，也即：在虚拟空间中找足够大的连续页面，将 fd 对应文件的前 length 字节存储在">
<meta property="og:type" content="article">
<meta property="og:title" content="xv6 实验十 mmap">
<meta property="og:url" content="https://kilogrand.gitee.io/2022/09/09/xv6-lab10/index.html">
<meta property="og:site_name" content="kiloGrand">
<meta property="og:description" content="https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;schedule.html https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;labs&#x2F;mmap.html  本次实验只需实现简化版的 mmap和munmap  保证 addr 和 offset 都为 0，也即：在虚拟空间中找足够大的连续页面，将 fd 对应文件的前 length 字节存储在">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kilogrand.gitee.io/img/coding.jpg">
<meta property="article:published_time" content="2022-09-09T01:41:10.000Z">
<meta property="article:modified_time" content="2023-03-15T05:46:59.095Z">
<meta property="article:author" content="kiloGrand">
<meta property="article:tag" content="xv6">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kilogrand.gitee.io/img/coding.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kilogrand.gitee.io/2022/09/09/xv6-lab10/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'xv6 实验十 mmap',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-15 13:46:59'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/profile.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/coding.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">kiloGrand</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">xv6 实验十 mmap</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-09-09T01:41:10.000Z" title="发表于 2022-09-09 09:41:10">2022-09-09</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-15T05:46:59.095Z" title="更新于 2023-03-15 13:46:59">2023-03-15</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>24分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="xv6 实验十 mmap"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><ul>
<li><a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.S081/2020/schedule.html">https://pdos.csail.mit.edu/6.S081/2020/schedule.html</a></li>
<li><a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.S081/2020/labs/mmap.html">https://pdos.csail.mit.edu/6.S081/2020/labs/mmap.html</a></li>
</ul>
<p>本次实验只需实现简化版的 <code>mmap</code>和<code>munmap</code></p>
<ul>
<li>保证 <code>addr</code> 和 <code>offset</code> 都为 0，也即：在虚拟空间中找足够大的连续页面，将 fd 对应文件的前 length 字节存储在里面。</li>
<li><code>flags</code> 只需考虑 <code>MAP_SHARED</code> 和 <code>MAP_PRIVATE</code>；<code>prot</code> 只需考虑 <code>PROT_WRITE</code> 和 <code>PROT_READ</code>。</li>
<li>允许不同进程把同一个 <code>MAP_SHARED</code> 的文件映射到不同的物理页面上。</li>
<li><code>munmap</code> 释放的范围保证是一段 <code>mmap</code> 了的空间的开头一段、或结尾一段、或全部，不会从中间挖一个洞出来。</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> *<span class="title function_">mmap</span><span class="params">(<span class="type">void</span> *addr, <span class="type">size_t</span> length, <span class="type">int</span> prot, <span class="type">int</span> flags, <span class="type">int</span> fd, <span class="type">off_t</span> offset)</span>;</span><br><span class="line"><span class="type">int</span> <span class="title function_">munmap</span><span class="params">(<span class="type">void</span> *addr, <span class="type">size_t</span> len)</span>;</span><br></pre></td></tr></table></figure>
<h2 id="定义每个进程的VMA（虚拟内存区域）"><a href="#定义每个进程的VMA（虚拟内存区域）" class="headerlink" title="定义每个进程的VMA（虚拟内存区域）"></a>定义每个进程的VMA（虚拟内存区域）</h2><p>首先设计一个数据结构 VMA，记录 mmap 分配的虚拟内存空间，包括地址、长度、权限等等信息：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/pro.h</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> &#123;</span></span><br><span class="line">  <span class="type">int</span> shared;</span><br><span class="line">  <span class="type">int</span> perm;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">file</span> *<span class="title">filept</span>;</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> *<span class="title">nxt</span>;</span></span><br><span class="line">  <span class="type">int</span> valid;</span><br><span class="line">  uint64 vmstart, vmend;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Per-process state</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">proc</span> &#123;</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">spinlock</span> <span class="title">lock</span>;</span></span><br><span class="line">  ......</span><br><span class="line">  <span class="type">char</span> name[<span class="number">16</span>];               <span class="comment">// Process name (debugging)</span></span><br><span class="line"> </span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> *<span class="title">vmalist</span>;</span>      <span class="comment">// linklist of vma</span></span><br><span class="line">  uint64 curmax;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><br>这里，我并没有直接记录 mmap 输入的变量，而是做了一些转换方便后续操作：</p>
<ul>
<li>shared 为 1 表示 MAP_SHARED，为 0 表示 MAP_PRIVATE</li>
<li>perm 指示 pte 的权限，即 PTE_W 或 PTE_R 或二者都有，根据 prot 设置</li>
<li>filept 是指向文件的指针，指向当前进程打开的描述符为 fd 的文件</li>
<li>valid 指示该 VMA 是否正在被某进程使用中</li>
<li>vmstart 和 vmend 是根据 addr 和 length 计算出来的与一页对齐的 vma 地址范围，因为我们分配内存空间一定是按页分配的</li>
<li>每一个进程的 PCB 中记录它用到的所有 VMA——我用了一个链表，所以有一个 nxt 指针字段</li>
</ul>
<p>如何确定VMA的开始和结束地址呢？<br>从高地址处向低地址找这样的“不用区域”，为此在每个 PCB 里记录一下已分配区域的最低地址 curmax，下次就从 curmax 继续往下分配。</p>
<p>开一个 VMA 全局数组（16 个即可），当某进程执行 mmap 系统调用时就从该数组中找一个 valid 无效的 VMA 分配给该进程：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/param.h</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> NVMA         16 <span class="comment">// maximum number of VMAs</span></span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/proc.c</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> &#123;</span> </span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">spinlock</span> <span class="title">lock</span>;</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> <span class="title">vmas</span>[<span class="title">NVMA</span>];</span></span><br><span class="line">&#125; vmatable;</span><br><span class="line"></span><br><span class="line"><span class="comment">// initialize the proc table at boot time.</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">procinit</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span>;</span></span><br><span class="line">  </span><br><span class="line">  initlock(&amp;pid_lock, <span class="string">&quot;nextpid&quot;</span>);</span><br><span class="line">  <span class="keyword">for</span>(p = proc; p &lt; &amp;proc[NPROC]; p++) &#123;</span><br><span class="line">      initlock(&amp;p-&gt;lock, <span class="string">&quot;proc&quot;</span>);</span><br><span class="line">      p-&gt;kstack = KSTACK((<span class="type">int</span>) (p - proc));</span><br><span class="line">      p-&gt;curmax = MAXVA - <span class="number">2</span> * PGSIZE; <span class="comment">// init curmax for vma</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">vmainit</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  initlock(&amp;vmatable.lock, <span class="string">&quot;vmatable&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">struct</span> VMA*</span><br><span class="line"><span class="title function_">allocvma</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  acquire(&amp;vmatable.lock);</span><br><span class="line">  <span class="type">int</span> i;</span><br><span class="line">  <span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; NVMA; i++)&#123;</span><br><span class="line">    <span class="keyword">if</span>(vmatable.vmas[i].valid)</span><br><span class="line">      <span class="keyword">continue</span>;</span><br><span class="line">    vmatable.vmas[i].valid = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  release(&amp;vmatable.lock);</span><br><span class="line">  <span class="keyword">if</span>(i == NVMA) panic(<span class="string">&quot;allocvma&quot;</span>);</span><br><span class="line">  <span class="keyword">return</span> vmatable.vmas + i;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">deallocvma</span><span class="params">(<span class="keyword">struct</span> VMA *vma)</span></span><br><span class="line">&#123;</span><br><span class="line">  acquire(&amp;vmatable.lock);</span><br><span class="line">  vma-&gt;valid = <span class="number">0</span>;</span><br><span class="line">  release(&amp;vmatable.lock);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/defs.h</span></span><br><span class="line">......</span><br><span class="line"><span class="type">void</span>            <span class="title function_">procdump</span><span class="params">(<span class="type">void</span>)</span>;</span><br><span class="line"><span class="type">void</span>            <span class="title function_">vmainit</span><span class="params">(<span class="type">void</span>)</span>; </span><br><span class="line"><span class="keyword">struct</span> VMA*     <span class="title function_">allocvma</span><span class="params">(<span class="type">void</span>)</span>;</span><br><span class="line"><span class="type">void</span>            <span class="title function_">deallocvma</span><span class="params">(<span class="keyword">struct</span> VMA *)</span>; </span><br></pre></td></tr></table></figure>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/main.c</span></span><br><span class="line">...</span><br><span class="line">    fileinit();      <span class="comment">// file table</span></span><br><span class="line">    vmainit();       <span class="comment">// vma table</span></span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>给多个进程分配 vma 显然是需要上锁的操作，我懒得麻烦就直接上全局锁了。</p>
<h2 id="sys-mmap-的实现"><a href="#sys-mmap-的实现" class="headerlink" title="sys_mmap 的实现"></a>sys_mmap 的实现</h2><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// user/user.h</span></span><br><span class="line">......</span><br><span class="line"><span class="type">int</span> <span class="title function_">uptime</span><span class="params">(<span class="type">void</span>)</span>;</span><br><span class="line"><span class="type">void</span> *<span class="title function_">mmap</span><span class="params">(<span class="type">void</span> *, <span class="type">int</span>, <span class="type">int</span>, <span class="type">int</span>, <span class="type">int</span>, <span class="type">int</span>)</span>;</span><br><span class="line"><span class="type">int</span> <span class="title function_">munmap</span><span class="params">(<span class="type">void</span> *, <span class="type">int</span>)</span>;</span><br><span class="line">......</span><br></pre></td></tr></table></figure>
<figure class="highlight pl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// user/usys.pl</span><br><span class="line">......</span><br><span class="line">entry(<span class="string">&quot;uptime&quot;</span>);</span><br><span class="line">entry(<span class="string">&quot;mmap&quot;</span>);</span><br><span class="line">entry(<span class="string">&quot;munmap&quot;</span>);</span><br></pre></td></tr></table></figure>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/syscall.h</span></span><br><span class="line">......</span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SYS_close  21</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SYS_mmap   22</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> SYS_munmap 23</span></span><br></pre></td></tr></table></figure>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/syscall.c</span></span><br><span class="line">......</span><br><span class="line"><span class="keyword">extern</span> uint64 <span class="title function_">sys_uptime</span><span class="params">(<span class="type">void</span>)</span>;</span><br><span class="line"><span class="keyword">extern</span> uint64 <span class="title function_">sys_mmap</span><span class="params">(<span class="type">void</span>)</span>;</span><br><span class="line"><span class="keyword">extern</span> uint64 <span class="title function_">sys_munmap</span><span class="params">(<span class="type">void</span>)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="title function_">uint64</span> <span class="params">(*syscalls[])</span><span class="params">(<span class="type">void</span>)</span> = &#123;</span><br><span class="line">......</span><br><span class="line">[SYS_close]   sys_close,</span><br><span class="line">[SYS_mmap]    sys_mmap,</span><br><span class="line">[SYS_munmap]  sys_munmap,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">UPROGS=\</span><br><span class="line">......</span><br><span class="line">	$U/_zombie\</span><br><span class="line">	$U/_mmaptest\</span><br></pre></td></tr></table></figure>
<p>首先分配一个 vma，按照上文所述含义填充 vma 的各个字段，注意要增加文件的 reference count，然后把这个 vma 加到进程的 vma 链表里面。mmap 是 lazy allocation 的，所以我们这时候无需 kalloc 物理内存，只需返回起始地址。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/sysfile.c</span></span><br><span class="line">uint64</span><br><span class="line"><span class="title function_">sys_mmap</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  uint64 addr;</span><br><span class="line">  <span class="type">int</span> length, prot, flags, fd, offset;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(argaddr(<span class="number">0</span>, &amp;addr) &lt; <span class="number">0</span> ||</span><br><span class="line">     argint(<span class="number">1</span>, &amp;length) &lt; <span class="number">0</span> ||</span><br><span class="line">     argint(<span class="number">2</span>, &amp;prot) &lt; <span class="number">0</span> ||</span><br><span class="line">     argint(<span class="number">3</span>, &amp;flags) &lt; <span class="number">0</span> ||</span><br><span class="line">     argint(<span class="number">4</span>, &amp;fd) &lt; <span class="number">0</span> ||</span><br><span class="line">     argint(<span class="number">5</span>, &amp;offset) &lt; <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="keyword">if</span>(addr != <span class="number">0</span>) panic(<span class="string">&quot;sys_mmap&quot;</span>);</span><br><span class="line">  <span class="keyword">if</span>(offset != <span class="number">0</span>) panic(<span class="string">&quot;sys_mmap&quot;</span>);</span><br><span class="line">  </span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">file</span> *<span class="title">f</span> =</span> p-&gt;ofile[fd];</span><br><span class="line">  <span class="keyword">if</span>((prot &amp; PROT_READ) &amp;&amp; !f-&gt;readable)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="keyword">if</span>((prot &amp; PROT_WRITE) &amp;&amp; (flags &amp; MAP_SHARED) &amp;&amp; !f-&gt;writable)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// alloc a vma</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> *<span class="title">vma</span> =</span> allocvma();</span><br><span class="line">  <span class="keyword">if</span>(!vma)  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="comment">// fill in vma</span></span><br><span class="line">  vma-&gt;perm = ((prot &amp; PROT_READ) ? PTE_R : <span class="number">0</span>) |</span><br><span class="line">              ((prot &amp; PROT_WRITE) ? PTE_W : <span class="number">0</span>);</span><br><span class="line">  vma-&gt;shared = (flags &amp; MAP_SHARED) ? <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">  vma-&gt;filept = f;</span><br><span class="line">  filedup(f);</span><br><span class="line">  <span class="comment">// add vma to process&#x27;s linklist</span></span><br><span class="line">  vma-&gt;nxt = p-&gt;vmalist;</span><br><span class="line">  p-&gt;vmalist = vma;</span><br><span class="line">  <span class="comment">// find an unused region in the process&#x27;s address space in which to map the file</span></span><br><span class="line">  uint64 vmaddr = PGROUNDDOWN(p-&gt;curmax - length);</span><br><span class="line">  <span class="keyword">if</span>(vmaddr % PGSIZE != <span class="number">0</span>)  panic(<span class="string">&quot;sys_mmap&quot;</span>);</span><br><span class="line">  vma-&gt;vmstart = vmaddr;</span><br><span class="line">  vma-&gt;vmend = p-&gt;curmax;</span><br><span class="line">  p-&gt;curmax = vmaddr;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> vmaddr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如前所述，mmap 是 lazy allocation 的，所以我们在 usertrap 里处理 page fault：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/trap.c</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">usertrap</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">if</span>(r_scause() == <span class="number">8</span>)&#123;</span><br><span class="line">    ...</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span>((which_dev = devintr()) != <span class="number">0</span>)&#123;</span><br><span class="line">    ...</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    uint64 cause = r_scause();</span><br><span class="line">    <span class="keyword">if</span>(cause == <span class="number">13</span> || cause == <span class="number">15</span>)&#123;</span><br><span class="line">      <span class="comment">// page fault</span></span><br><span class="line">      uint64 stval = r_stval();</span><br><span class="line">      <span class="keyword">if</span>(mmaplazy(stval, cause) == <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">goto</span> brk;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;usertrap(): unexpected scause %p pid=%d\n&quot;</span>, r_scause(), p-&gt;pid);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;            sepc=%p stval=%p\n&quot;</span>, r_sepc(), r_stval());</span><br><span class="line">    p-&gt;killed = <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">brk:</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>stval 就是产生 page fault 的地址，我们不需要读入整个文件，只需要申请并映射 stval 所在的那一页并读入这一页对应的文件数据即可：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/proc.c</span></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">mmaplazy</span><span class="params">(uint64 va, uint64 cause)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line">  <span class="comment">// find the corresponding vma</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> *<span class="title">vma</span> =</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span>(vma = p-&gt;vmalist; vma; vma = vma-&gt;nxt)</span><br><span class="line">    <span class="keyword">if</span>(vma-&gt;valid &amp;&amp; vma-&gt;vmstart &lt;= va &amp;&amp; va &lt; vma-&gt;vmend)</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">if</span>(!vma)  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="keyword">if</span>(cause == <span class="number">13</span> &amp;&amp; !(vma-&gt;perm &amp; PTE_R)) <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="keyword">if</span>(cause == <span class="number">15</span> &amp;&amp; !(vma-&gt;perm &amp; PTE_W)) <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="comment">// allocate physical memory and map pte</span></span><br><span class="line">  <span class="type">char</span> *mem = kalloc();</span><br><span class="line">  <span class="keyword">if</span>(mem == <span class="number">0</span>)  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="built_in">memset</span>(mem, <span class="number">0</span>, PGSIZE);</span><br><span class="line">  uint64 vaalign = PGROUNDDOWN(va);</span><br><span class="line">  <span class="keyword">if</span>(mappages(p-&gt;pagetable, vaalign, PGSIZE, (uint64)mem, vma-&gt;perm|PTE_U|PTE_X) != <span class="number">0</span>)&#123;</span><br><span class="line">    kfree(mem);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// read content of file into allocated memory</span></span><br><span class="line">  mmapfileread(vma-&gt;filept, <span class="number">0</span>, (uint64)mem, vaalign - vma-&gt;vmstart, PGSIZE);</span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/file.c</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mmapfileread</span><span class="params">(<span class="keyword">struct</span> file *f, <span class="type">int</span> user_dst, uint64 dst, uint off, uint n)</span>&#123; </span><br><span class="line">  ilock(f-&gt;ip);</span><br><span class="line">  <span class="type">int</span> ret = readi(f-&gt;ip, user_dst, dst, off, n);</span><br><span class="line">  iunlock(f-&gt;ip);</span><br><span class="line">  <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/defs.h</span></span><br><span class="line"><span class="type">int</span>             <span class="title function_">mmapfileread</span><span class="params">(<span class="keyword">struct</span> file*, <span class="type">int</span>, uint64, uint, uint)</span>;</span><br><span class="line"><span class="type">int</span>             <span class="title function_">mmaplazy</span><span class="params">(uint64, uint64)</span>; </span><br></pre></td></tr></table></figure>
<p>这里特别说明文件开始读的偏移位置 off 和读的长度 n 是怎么计算的，如图所示：<br><img src="xv6-lab10-1.png" alt=""><br>蓝色 va 是发生 pagefault 的地方，因此灰色页就是我们要读的页。绿色线段是文件占的大小，它一定从 vmstart 开始。从图上能直观的看出，我们要读的文件偏移量就是 vaalign-vmstart，又由于读一页，所以 n 就是 PGSIZE。</p>
<h2 id="munmap-的实现"><a href="#munmap-的实现" class="headerlink" title="munmap 的实现"></a>munmap 的实现</h2><ul>
<li>找到包含释放空间的 vma</li>
<li>如果 vma 是 shared 的，则把现在的内容写回文件</li>
<li>解除页表的映射</li>
<li>分情况更新 vma：如果释放的只是 vma 区域的一部分，则更新 vma 的 vmstart 和 vmend；如果释放了整个 vma 区域，则把它从链表里拿出来、释放（valid 置零）、减少文件 reference count。</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/sysfile.c</span></span><br><span class="line">uint64</span><br><span class="line"><span class="title function_">sys_munmap</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  uint64 addr;</span><br><span class="line">  <span class="type">int</span> length;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(argaddr(<span class="number">0</span>, &amp;addr) &lt; <span class="number">0</span> || argint(<span class="number">1</span>, &amp;length) &lt; <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// find the VMA for the address range</span></span><br><span class="line">  uint64 st = PGROUNDDOWN(addr);</span><br><span class="line">  uint64 ed = PGROUNDUP(addr + length);</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> *<span class="title">vma</span> =</span> <span class="number">0</span>, *pre = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span>(vma = p-&gt;vmalist; vma; vma = vma-&gt;nxt)&#123;</span><br><span class="line">    <span class="keyword">if</span>(vma-&gt;valid &amp;&amp; vma-&gt;vmstart &lt;= st &amp;&amp; ed &lt;= vma-&gt;vmend)</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    pre = vma;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>(!vma)  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// write back if needed</span></span><br><span class="line">  <span class="keyword">if</span>(vma-&gt;shared &amp;&amp; (vma-&gt;perm | PTE_W))</span><br><span class="line">    mmapfilewrite(vma-&gt;filept, st, ed - st);</span><br><span class="line">  <span class="comment">// unmap specified pages</span></span><br><span class="line">  <span class="keyword">for</span>(uint64 i = st; i &lt; ed; i += PGSIZE)&#123;</span><br><span class="line">    <span class="keyword">if</span>(walkaddr(p-&gt;pagetable, i))&#123;</span><br><span class="line">      <span class="comment">// need to check because vma is allocated lazily</span></span><br><span class="line">      uvmunmap(p-&gt;pagetable, i, <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// update info in vma</span></span><br><span class="line">  <span class="keyword">if</span>(vma-&gt;vmstart == st &amp;&amp; ed &lt; vma-&gt;vmend)</span><br><span class="line">    vma-&gt;vmstart = PGROUNDDOWN(addr + length);</span><br><span class="line">  <span class="keyword">else</span> <span class="keyword">if</span>(vma-&gt;vmstart &lt; st &amp;&amp; ed == vma-&gt;vmend)</span><br><span class="line">    vma-&gt;vmend = PGROUNDUP(addr);</span><br><span class="line">  <span class="keyword">else</span> <span class="keyword">if</span>(vma-&gt;vmstart == st &amp;&amp; ed == vma-&gt;vmend)&#123;</span><br><span class="line">    <span class="keyword">if</span>(pre == <span class="number">0</span>)  p-&gt;vmalist = vma-&gt;nxt;</span><br><span class="line">    <span class="keyword">else</span>  pre-&gt;nxt = vma-&gt;nxt, vma-&gt;nxt = <span class="number">0</span>;</span><br><span class="line">    fileclose(vma-&gt;filept);</span><br><span class="line">    deallocvma(vma);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">else</span> ;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/file.c</span></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">mmapfilewrite</span><span class="params">(<span class="keyword">struct</span> file *f, uint64 addr, uint n)</span>&#123;</span><br><span class="line">  <span class="type">int</span> max = ((MAXOPBLOCKS<span class="number">-1</span><span class="number">-1</span><span class="number">-2</span>) / <span class="number">2</span>) * BSIZE;</span><br><span class="line">  <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">while</span>(i &lt; n)&#123;</span><br><span class="line">    <span class="type">int</span> n1 = n - i;</span><br><span class="line">    <span class="keyword">if</span>(n1 &gt; max)</span><br><span class="line">      n1 = max;</span><br><span class="line"></span><br><span class="line">    begin_op();</span><br><span class="line">    ilock(f-&gt;ip);</span><br><span class="line">    <span class="type">int</span> r = writei(f-&gt;ip, <span class="number">1</span>, addr + i, i, n1);</span><br><span class="line">    iunlock(f-&gt;ip);</span><br><span class="line">    end_op();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(r != n1)&#123;</span><br><span class="line">      <span class="comment">// error from writei</span></span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    i += r;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="type">int</span> ret = (i == n ? n : <span class="number">-1</span>);</span><br><span class="line">  <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>值得注意的是，解除页表映射前一定先 walk 一下，因为我们是 lazy allocation，释放空间里的页面不一定全部都已经建立了映射。</p>
<p>还有一个点，如果释放区域是 vma 开头或者结尾区域，那怎么调整 vmstart 或 vmend 呢？看图说话：<br><img src="xv6-lab10-2.png" alt=""><br>理论上来说，释放了 vma 一部分后，这部分空间可以拿出来再次分配（垃圾回收），或者可以进行内存紧缩。我并没有实现它们，这是可以继续改进的一点。</p>
<p>最后，在 exit 中释放掉该进程的所有 vma，要干的事和 munmap 差不多：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/proc.c</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">exit</span><span class="params">(<span class="type">int</span> status)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> *<span class="title">vma</span> =</span> <span class="number">0</span>, *nxtvma = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span>(vma = p-&gt;vmalist; vma; vma = nxtvma)&#123;</span><br><span class="line">    nxtvma = vma-&gt;nxt;</span><br><span class="line">    <span class="keyword">for</span>(uint64 i = vma-&gt;vmstart; i &lt; vma-&gt;vmend; i += PGSIZE)</span><br><span class="line">      <span class="keyword">if</span>(walkaddr(p-&gt;pagetable, i))</span><br><span class="line">        uvmunmap(p-&gt;pagetable, i, <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">    vma-&gt;nxt = <span class="number">0</span>;</span><br><span class="line">    fileclose(vma-&gt;filept);</span><br><span class="line">    deallocvma(vma);</span><br><span class="line">  &#125;</span><br><span class="line">  p-&gt;vmalist = <span class="number">0</span>;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>以及在 fork 的时候把 vma 给到子进程，要干的事和 mmap 差不多：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">fork</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> *<span class="title">vma</span> =</span> <span class="number">0</span>, *pre = <span class="number">0</span>;</span><br><span class="line">  np-&gt;vmalist = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span>(vma = p-&gt;vmalist; vma; vma = vma-&gt;nxt)&#123;</span><br><span class="line">    <span class="comment">// alloc a vma</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">VMA</span> *<span class="title">newvma</span> =</span> allocvma();</span><br><span class="line">    <span class="comment">// fill in newvma</span></span><br><span class="line">    newvma-&gt;shared = vma-&gt;shared;</span><br><span class="line">    newvma-&gt;perm = vma-&gt;perm;</span><br><span class="line">    newvma-&gt;filept = vma-&gt;filept;</span><br><span class="line">    newvma-&gt;vmstart = vma-&gt;vmstart;</span><br><span class="line">    newvma-&gt;vmend = vma-&gt;vmend;</span><br><span class="line">    filedup(vma-&gt;filept);</span><br><span class="line">    <span class="comment">// add newvma to np&#x27;s linklist</span></span><br><span class="line">    <span class="keyword">if</span>(pre == <span class="number">0</span>)  np-&gt;vmalist = newvma;</span><br><span class="line">    <span class="keyword">else</span>  pre-&gt;nxt = newvma, newvma-&gt;nxt = <span class="number">0</span>;</span><br><span class="line">    pre = newvma;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="make-grade"><a href="#make-grade" class="headerlink" title="make grade"></a>make grade</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">grand@Lubuntu ~/xv6-labs-2020 (mmap)&gt; ./grade-lab-mmap</span><br><span class="line">make: <span class="string">&#x27;kernel/kernel&#x27;</span> is up to <span class="built_in">date</span>.</span><br><span class="line">== Test running mmaptest == (6.1s) </span><br><span class="line">== Test   mmaptest: mmap f == </span><br><span class="line">  mmaptest: mmap f: OK </span><br><span class="line">== Test   mmaptest: mmap private == </span><br><span class="line">  mmaptest: mmap private: OK </span><br><span class="line">== Test   mmaptest: mmap read-only == </span><br><span class="line">  mmaptest: mmap read-only: OK </span><br><span class="line">== Test   mmaptest: mmap <span class="built_in">read</span>/write == </span><br><span class="line">  mmaptest: mmap <span class="built_in">read</span>/write: OK </span><br><span class="line">== Test   mmaptest: mmap dirty == </span><br><span class="line">  mmaptest: mmap dirty: OK </span><br><span class="line">== Test   mmaptest: not-mapped unmap == </span><br><span class="line">  mmaptest: not-mapped unmap: OK </span><br><span class="line">== Test   mmaptest: two files == </span><br><span class="line">  mmaptest: two files: OK </span><br><span class="line">== Test   mmaptest: fork_test == </span><br><span class="line">  mmaptest: fork_test: OK </span><br><span class="line">== Test usertests == usertests: OK (445.9s) </span><br><span class="line">    (Old xv6.out.usertests failure <span class="built_in">log</span> removed)</span><br><span class="line">== Test time == </span><br><span class="line">time: OK </span><br><span class="line">Score: 140/140</span><br></pre></td></tr></table></figure>
<h2 id="git-diff"><a href="#git-diff" class="headerlink" title="git diff"></a>git diff</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br><span class="line">415</span><br><span class="line">416</span><br><span class="line">417</span><br><span class="line">418</span><br><span class="line">419</span><br><span class="line">420</span><br><span class="line">421</span><br><span class="line">422</span><br><span class="line">423</span><br><span class="line">424</span><br><span class="line">425</span><br><span class="line">426</span><br><span class="line">427</span><br><span class="line">428</span><br><span class="line">429</span><br><span class="line">430</span><br><span class="line">431</span><br><span class="line">432</span><br><span class="line">433</span><br><span class="line">434</span><br><span class="line">435</span><br><span class="line">436</span><br><span class="line">437</span><br><span class="line">438</span><br><span class="line">439</span><br><span class="line">440</span><br><span class="line">441</span><br><span class="line">442</span><br><span class="line">443</span><br><span class="line">444</span><br><span class="line">445</span><br><span class="line">446</span><br><span class="line">447</span><br><span class="line">448</span><br><span class="line">449</span><br><span class="line">450</span><br><span class="line">451</span><br><span class="line">452</span><br><span class="line">453</span><br><span class="line">454</span><br></pre></td><td class="code"><pre><span class="line">diff --git a/Makefile b/Makefile</span><br><span class="line">index d8509b1..31803d4 100644</span><br><span class="line">--- a/Makefile</span><br><span class="line">+++ b/Makefile</span><br><span class="line">@@ -175,6 +175,7 @@ UPROGS=\</span><br><span class="line"> 	<span class="variable">$U</span>/_grind\</span><br><span class="line"> 	<span class="variable">$U</span>/_wc\</span><br><span class="line"> 	<span class="variable">$U</span>/_zombie\</span><br><span class="line">+	<span class="variable">$U</span>/_mmaptest\</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">diff --git a/grade-lab-mmap b/grade-lab-mmap</span><br><span class="line">index f1a67bb..9313312 100755</span><br><span class="line">--- a/grade-lab-mmap</span><br><span class="line">+++ b/grade-lab-mmap</span><br><span class="line">@@ -47,7 +47,7 @@ def test_mmaptest_fork_test():</span><br><span class="line"> def test_usertests():</span><br><span class="line">     r.run_qemu(shell_script([</span><br><span class="line">         <span class="string">&#x27;usertests&#x27;</span></span><br><span class="line">-    ]), <span class="built_in">timeout</span>=300)</span><br><span class="line">+    ]), <span class="built_in">timeout</span>=1000)</span><br><span class="line">     r.match(<span class="string">&#x27;^ALL TESTS PASSED$&#x27;</span>)</span><br><span class="line"> </span><br><span class="line"> @<span class="built_in">test</span>(1, <span class="string">&quot;time&quot;</span>)</span><br><span class="line">diff --git a/kernel/defs.h b/kernel/defs.h</span><br><span class="line">index 41098f4..51f05dd 100644</span><br><span class="line">--- a/kernel/defs.h</span><br><span class="line">+++ b/kernel/defs.h</span><br><span class="line">@@ -33,6 +33,8 @@ void            fileinit(void);</span><br><span class="line"> int             fileread(struct file*, uint64, int n);</span><br><span class="line"> int             filestat(struct file*, uint64 addr);</span><br><span class="line"> int             filewrite(struct file*, uint64, int n);</span><br><span class="line">+int             mmapfileread(struct file*, int, uint64, uint, uint);</span><br><span class="line">+int             mmapfilewrite(struct file*, uint64, uint);</span><br><span class="line"> </span><br><span class="line"> // fs.c</span><br><span class="line"> void            fsinit(int);</span><br><span class="line">@@ -105,6 +107,10 @@ void            yield(void);</span><br><span class="line"> int             either_copyout(int user_dst, uint64 dst, void *src, uint64 len);</span><br><span class="line"> int             either_copyin(void *dst, int user_src, uint64 src, uint64 len);</span><br><span class="line"> void            procdump(void);</span><br><span class="line">+void            vmainit(void); </span><br><span class="line">+struct VMA*     allocvma(void);</span><br><span class="line">+void            deallocvma(struct VMA *);</span><br><span class="line">+int             mmaplazy(uint64, uint64); </span><br><span class="line"> </span><br><span class="line"> // swtch.S</span><br><span class="line"> void            swtch(struct context*, struct context*);</span><br><span class="line">diff --git a/kernel/file.c b/kernel/file.c</span><br><span class="line">index 25fa226..6a6d5ef 100644</span><br><span class="line">--- a/kernel/file.c</span><br><span class="line">+++ b/kernel/file.c</span><br><span class="line">@@ -180,3 +180,35 @@ filewrite(struct file *f, uint64 addr, int n)</span><br><span class="line">   <span class="built_in">return</span> ret;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line">+int </span><br><span class="line">+mmapfileread(struct file *f, int user_dst, uint64 dst, uint off, uint n)&#123; </span><br><span class="line">+  ilock(f-&gt;ip);</span><br><span class="line">+  int ret = readi(f-&gt;ip, user_dst, dst, off, n);</span><br><span class="line">+  iunlock(f-&gt;ip);</span><br><span class="line">+  <span class="built_in">return</span> ret;</span><br><span class="line">+&#125;</span><br><span class="line">+</span><br><span class="line">+int </span><br><span class="line">+mmapfilewrite(struct file *f, uint64 addr, uint n)&#123;</span><br><span class="line">+  int max = ((MAXOPBLOCKS-1-1-2) / 2) * BSIZE;</span><br><span class="line">+  int i = 0;</span><br><span class="line">+  <span class="keyword">while</span>(i &lt; n)&#123;</span><br><span class="line">+    int n1 = n - i;</span><br><span class="line">+    <span class="keyword">if</span>(n1 &gt; max)</span><br><span class="line">+      n1 = max;</span><br><span class="line">+</span><br><span class="line">+    begin_op();</span><br><span class="line">+    ilock(f-&gt;ip);</span><br><span class="line">+    int r = writei(f-&gt;ip, 1, addr + i, i, n1);</span><br><span class="line">+    iunlock(f-&gt;ip);</span><br><span class="line">+    end_op();</span><br><span class="line">+</span><br><span class="line">+    <span class="keyword">if</span>(r != n1)&#123;</span><br><span class="line">+      // error from writei</span><br><span class="line">+      <span class="built_in">break</span>;</span><br><span class="line">+    &#125;</span><br><span class="line">+    i += r;</span><br><span class="line">+  &#125;</span><br><span class="line">+  int ret = (i == n ? n : -1);</span><br><span class="line">+  <span class="built_in">return</span> ret;</span><br><span class="line">+&#125;</span><br><span class="line">diff --git a/kernel/main.c b/kernel/main.c</span><br><span class="line">index 5d7ad49..e4e7013 100644</span><br><span class="line">--- a/kernel/main.c</span><br><span class="line">+++ b/kernel/main.c</span><br><span class="line">@@ -27,6 +27,7 @@ main()</span><br><span class="line">     binit();         // buffer cache</span><br><span class="line">     iinit();         // inode cache</span><br><span class="line">     fileinit();      // file table</span><br><span class="line">+    vmainit();       // vma table</span><br><span class="line">     virtio_disk_init(); // emulated hard disk</span><br><span class="line">     userinit();      // first user process</span><br><span class="line">     __sync_synchronize();</span><br><span class="line">diff --git a/kernel/param.h b/kernel/param.h</span><br><span class="line">index b5fdcb2..b51db5c 100644</span><br><span class="line">--- a/kernel/param.h</span><br><span class="line">+++ b/kernel/param.h</span><br><span class="line">@@ -11,3 +11,4 @@</span><br><span class="line"> <span class="comment">#define NBUF         (MAXOPBLOCKS*3)  // size of disk block cache</span></span><br><span class="line"> <span class="comment">#define FSSIZE       1000  // size of file system in blocks</span></span><br><span class="line"> <span class="comment">#define MAXPATH      128   // maximum file path name</span></span><br><span class="line">+<span class="comment">#define NVMA         16  // maximum number of VMAs</span></span><br><span class="line">diff --git a/kernel/proc.c b/kernel/proc.c</span><br><span class="line">index ba1a9e3..8626dab 100644</span><br><span class="line">--- a/kernel/proc.c</span><br><span class="line">+++ b/kernel/proc.c</span><br><span class="line">@@ -12,6 +12,11 @@ struct proc proc[NPROC];</span><br><span class="line"> </span><br><span class="line"> struct proc *initproc;</span><br><span class="line"> </span><br><span class="line">+struct &#123;</span><br><span class="line">+  struct spinlock lock;</span><br><span class="line">+  struct VMA vmas[NVMA];</span><br><span class="line">+&#125; vmatable;</span><br><span class="line">+</span><br><span class="line"> int nextpid = 1;</span><br><span class="line"> struct spinlock pid_lock;</span><br><span class="line"> </span><br><span class="line">@@ -48,6 +53,7 @@ procinit(void)</span><br><span class="line">   <span class="keyword">for</span>(p = proc; p &lt; &amp;proc[NPROC]; p++) &#123;</span><br><span class="line">       initlock(&amp;p-&gt;lock, <span class="string">&quot;proc&quot;</span>);</span><br><span class="line">       p-&gt;kstack = KSTACK((int) (p - proc));</span><br><span class="line">+      p-&gt;curmax = MAXVA - 2 * PGSIZE; // init curmax <span class="keyword">for</span> vma</span><br><span class="line">   &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line">@@ -300,6 +306,24 @@ fork(void)</span><br><span class="line"> </span><br><span class="line">   pid = np-&gt;pid;</span><br><span class="line"> </span><br><span class="line">+  struct VMA *vma = 0, *pre = 0;</span><br><span class="line">+  np-&gt;vmalist = 0;</span><br><span class="line">+  <span class="keyword">for</span>(vma = p-&gt;vmalist; vma; vma = vma-&gt;nxt)&#123;</span><br><span class="line">+    // alloc a vma</span><br><span class="line">+    struct VMA *newvma = allocvma();</span><br><span class="line">+    // fill <span class="keyword">in</span> newvma</span><br><span class="line">+    newvma-&gt;shared = vma-&gt;shared;</span><br><span class="line">+    newvma-&gt;perm = vma-&gt;perm;</span><br><span class="line">+    newvma-&gt;filept = vma-&gt;filept;</span><br><span class="line">+    newvma-&gt;vmstart = vma-&gt;vmstart;</span><br><span class="line">+    newvma-&gt;vmend = vma-&gt;vmend;</span><br><span class="line">+    filedup(vma-&gt;filept);</span><br><span class="line">+    // add newvma to np<span class="string">&#x27;s linklist</span></span><br><span class="line"><span class="string">+    if(pre == 0)  np-&gt;vmalist = newvma;</span></span><br><span class="line"><span class="string">+    else  pre-&gt;nxt = newvma, newvma-&gt;nxt = 0;</span></span><br><span class="line"><span class="string">+    pre = newvma;</span></span><br><span class="line"><span class="string">+  &#125;</span></span><br><span class="line"><span class="string">+  </span></span><br><span class="line"><span class="string">   np-&gt;state = RUNNABLE;</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string">   release(&amp;np-&gt;lock);</span></span><br><span class="line"><span class="string">@@ -344,6 +368,18 @@ exit(int status)</span></span><br><span class="line"><span class="string">   if(p == initproc)</span></span><br><span class="line"><span class="string">     panic(&quot;init exiting&quot;);</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string">+  struct VMA *vma = 0, *nxtvma = 0;</span></span><br><span class="line"><span class="string">+  for(vma = p-&gt;vmalist; vma; vma = nxtvma)&#123;</span></span><br><span class="line"><span class="string">+    nxtvma = vma-&gt;nxt;</span></span><br><span class="line"><span class="string">+    for(uint64 i = vma-&gt;vmstart; i &lt; vma-&gt;vmend; i += PGSIZE)</span></span><br><span class="line"><span class="string">+      if(walkaddr(p-&gt;pagetable, i))</span></span><br><span class="line"><span class="string">+        uvmunmap(p-&gt;pagetable, i, 1, 1);</span></span><br><span class="line"><span class="string">+    vma-&gt;nxt = 0;</span></span><br><span class="line"><span class="string">+    fileclose(vma-&gt;filept);</span></span><br><span class="line"><span class="string">+    deallocvma(vma);</span></span><br><span class="line"><span class="string">+  &#125;</span></span><br><span class="line"><span class="string">+  p-&gt;vmalist = 0;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">   // Close all open files.</span></span><br><span class="line"><span class="string">   for(int fd = 0; fd &lt; NOFILE; fd++)&#123;</span></span><br><span class="line"><span class="string">     if(p-&gt;ofile[fd])&#123;</span></span><br><span class="line"><span class="string">@@ -701,3 +737,59 @@ procdump(void)</span></span><br><span class="line"><span class="string">     printf(&quot;\n&quot;);</span></span><br><span class="line"><span class="string">   &#125;</span></span><br><span class="line"><span class="string"> &#125;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+void</span></span><br><span class="line"><span class="string">+vmainit(void)</span></span><br><span class="line"><span class="string">+&#123;</span></span><br><span class="line"><span class="string">+  initlock(&amp;vmatable.lock, &quot;vmatable&quot;);</span></span><br><span class="line"><span class="string">+&#125;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+struct VMA*</span></span><br><span class="line"><span class="string">+allocvma(void)</span></span><br><span class="line"><span class="string">+&#123;</span></span><br><span class="line"><span class="string">+  acquire(&amp;vmatable.lock);</span></span><br><span class="line"><span class="string">+  int i;</span></span><br><span class="line"><span class="string">+  for(i = 0; i &lt; NVMA; i++)&#123;</span></span><br><span class="line"><span class="string">+    if(vmatable.vmas[i].valid)</span></span><br><span class="line"><span class="string">+      continue;</span></span><br><span class="line"><span class="string">+    vmatable.vmas[i].valid = 1;</span></span><br><span class="line"><span class="string">+    break;</span></span><br><span class="line"><span class="string">+  &#125;</span></span><br><span class="line"><span class="string">+  release(&amp;vmatable.lock);</span></span><br><span class="line"><span class="string">+  if(i == NVMA) panic(&quot;allocvma&quot;);</span></span><br><span class="line"><span class="string">+  return vmatable.vmas + i;</span></span><br><span class="line"><span class="string">+&#125;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+void</span></span><br><span class="line"><span class="string">+deallocvma(struct VMA *vma)</span></span><br><span class="line"><span class="string">+&#123;</span></span><br><span class="line"><span class="string">+  acquire(&amp;vmatable.lock);</span></span><br><span class="line"><span class="string">+  vma-&gt;valid = 0;</span></span><br><span class="line"><span class="string">+  release(&amp;vmatable.lock);</span></span><br><span class="line"><span class="string">+&#125;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+int</span></span><br><span class="line"><span class="string">+mmaplazy(uint64 va, uint64 cause)</span></span><br><span class="line"><span class="string">+&#123;</span></span><br><span class="line"><span class="string">+  struct proc *p = myproc();</span></span><br><span class="line"><span class="string">+  // find the corresponding vma</span></span><br><span class="line"><span class="string">+  struct VMA *vma = 0;</span></span><br><span class="line"><span class="string">+  for(vma = p-&gt;vmalist; vma; vma = vma-&gt;nxt)</span></span><br><span class="line"><span class="string">+    if(vma-&gt;valid &amp;&amp; vma-&gt;vmstart &lt;= va &amp;&amp; va &lt; vma-&gt;vmend)</span></span><br><span class="line"><span class="string">+      break;</span></span><br><span class="line"><span class="string">+  if(!vma)  return -1;</span></span><br><span class="line"><span class="string">+  if(cause == 13 &amp;&amp; !(vma-&gt;perm &amp; PTE_R)) return -1;</span></span><br><span class="line"><span class="string">+  if(cause == 15 &amp;&amp; !(vma-&gt;perm &amp; PTE_W)) return -1;</span></span><br><span class="line"><span class="string">+  // allocate physical memory and map pte</span></span><br><span class="line"><span class="string">+  char *mem = kalloc();</span></span><br><span class="line"><span class="string">+  if(mem == 0)  return -1;</span></span><br><span class="line"><span class="string">+  memset(mem, 0, PGSIZE);</span></span><br><span class="line"><span class="string">+  uint64 vaalign = PGROUNDDOWN(va);</span></span><br><span class="line"><span class="string">+  if(mappages(p-&gt;pagetable, vaalign, PGSIZE, (uint64)mem, vma-&gt;perm|PTE_U|PTE_X) != 0)&#123;</span></span><br><span class="line"><span class="string">+    kfree(mem);</span></span><br><span class="line"><span class="string">+    return -1;</span></span><br><span class="line"><span class="string">+  &#125;</span></span><br><span class="line"><span class="string">+  // read content of file into allocated memory</span></span><br><span class="line"><span class="string">+  mmapfileread(vma-&gt;filept, 0, (uint64)mem, vaalign - vma-&gt;vmstart, PGSIZE);</span></span><br><span class="line"><span class="string">+  return 0;</span></span><br><span class="line"><span class="string">+&#125;</span></span><br><span class="line"><span class="string">diff --git a/kernel/proc.h b/kernel/proc.h</span></span><br><span class="line"><span class="string">index 9c16ea7..a61a9fe 100644</span></span><br><span class="line"><span class="string">--- a/kernel/proc.h</span></span><br><span class="line"><span class="string">+++ b/kernel/proc.h</span></span><br><span class="line"><span class="string">@@ -82,6 +82,15 @@ struct trapframe &#123;</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string"> enum procstate &#123; UNUSED, SLEEPING, RUNNABLE, RUNNING, ZOMBIE &#125;;</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string">+struct VMA &#123;</span></span><br><span class="line"><span class="string">+  int shared;</span></span><br><span class="line"><span class="string">+  int perm;</span></span><br><span class="line"><span class="string">+  struct file *filept;</span></span><br><span class="line"><span class="string">+  struct VMA *nxt;</span></span><br><span class="line"><span class="string">+  int valid;</span></span><br><span class="line"><span class="string">+  uint64 vmstart, vmend;</span></span><br><span class="line"><span class="string">+&#125;;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string"> // Per-process state</span></span><br><span class="line"><span class="string"> struct proc &#123;</span></span><br><span class="line"><span class="string">   struct spinlock lock;</span></span><br><span class="line"><span class="string">@@ -103,4 +112,7 @@ struct proc &#123;</span></span><br><span class="line"><span class="string">   struct file *ofile[NOFILE];  // Open files</span></span><br><span class="line"><span class="string">   struct inode *cwd;           // Current directory</span></span><br><span class="line"><span class="string">   char name[16];               // Process name (debugging)</span></span><br><span class="line"><span class="string">+  </span></span><br><span class="line"><span class="string">+  struct VMA *vmalist;         // linklist of vma</span></span><br><span class="line"><span class="string">+  uint64 curmax;</span></span><br><span class="line"><span class="string"> &#125;;</span></span><br><span class="line"><span class="string">diff --git a/kernel/syscall.c b/kernel/syscall.c</span></span><br><span class="line"><span class="string">index c1b3670..7320633 100644</span></span><br><span class="line"><span class="string">--- a/kernel/syscall.c</span></span><br><span class="line"><span class="string">+++ b/kernel/syscall.c</span></span><br><span class="line"><span class="string">@@ -104,6 +104,8 @@ extern uint64 sys_unlink(void);</span></span><br><span class="line"><span class="string"> extern uint64 sys_wait(void);</span></span><br><span class="line"><span class="string"> extern uint64 sys_write(void);</span></span><br><span class="line"><span class="string"> extern uint64 sys_uptime(void);</span></span><br><span class="line"><span class="string">+extern uint64 sys_mmap(void);</span></span><br><span class="line"><span class="string">+extern uint64 sys_munmap(void);</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string"> static uint64 (*syscalls[])(void) = &#123;</span></span><br><span class="line"><span class="string"> [SYS_fork]    sys_fork,</span></span><br><span class="line"><span class="string">@@ -127,6 +129,8 @@ static uint64 (*syscalls[])(void) = &#123;</span></span><br><span class="line"><span class="string"> [SYS_link]    sys_link,</span></span><br><span class="line"><span class="string"> [SYS_mkdir]   sys_mkdir,</span></span><br><span class="line"><span class="string"> [SYS_close]   sys_close,</span></span><br><span class="line"><span class="string">+[SYS_mmap]    sys_mmap,</span></span><br><span class="line"><span class="string">+[SYS_munmap]  sys_munmap,</span></span><br><span class="line"><span class="string"> &#125;;</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string"> void</span></span><br><span class="line"><span class="string">diff --git a/kernel/syscall.h b/kernel/syscall.h</span></span><br><span class="line"><span class="string">index bc5f356..e7b18d6 100644</span></span><br><span class="line"><span class="string">--- a/kernel/syscall.h</span></span><br><span class="line"><span class="string">+++ b/kernel/syscall.h</span></span><br><span class="line"><span class="string">@@ -20,3 +20,5 @@</span></span><br><span class="line"><span class="string"> #define SYS_link   19</span></span><br><span class="line"><span class="string"> #define SYS_mkdir  20</span></span><br><span class="line"><span class="string"> #define SYS_close  21</span></span><br><span class="line"><span class="string">+#define SYS_mmap   22</span></span><br><span class="line"><span class="string">+#define SYS_munmap 23</span></span><br><span class="line"><span class="string">diff --git a/kernel/sysfile.c b/kernel/sysfile.c</span></span><br><span class="line"><span class="string">index 5dc453b..ef72c9a 100644</span></span><br><span class="line"><span class="string">--- a/kernel/sysfile.c</span></span><br><span class="line"><span class="string">+++ b/kernel/sysfile.c</span></span><br><span class="line"><span class="string">@@ -484,3 +484,95 @@ sys_pipe(void)</span></span><br><span class="line"><span class="string">   &#125;</span></span><br><span class="line"><span class="string">   return 0;</span></span><br><span class="line"><span class="string"> &#125;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+uint64</span></span><br><span class="line"><span class="string">+sys_mmap(void)</span></span><br><span class="line"><span class="string">+&#123;</span></span><br><span class="line"><span class="string">+  uint64 addr;</span></span><br><span class="line"><span class="string">+  int length, prot, flags, fd, offset;</span></span><br><span class="line"><span class="string">+  struct proc *p = myproc();</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+  if(argaddr(0, &amp;addr) &lt; 0 ||</span></span><br><span class="line"><span class="string">+     argint(1, &amp;length) &lt; 0 ||</span></span><br><span class="line"><span class="string">+     argint(2, &amp;prot) &lt; 0 ||</span></span><br><span class="line"><span class="string">+     argint(3, &amp;flags) &lt; 0 ||</span></span><br><span class="line"><span class="string">+     argint(4, &amp;fd) &lt; 0 ||</span></span><br><span class="line"><span class="string">+     argint(5, &amp;offset) &lt; 0)</span></span><br><span class="line"><span class="string">+    return -1;</span></span><br><span class="line"><span class="string">+  if(addr != 0) panic(&quot;sys_mmap&quot;);</span></span><br><span class="line"><span class="string">+  if(offset != 0) panic(&quot;sys_mmap&quot;);</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+  struct file *f = p-&gt;ofile[fd];</span></span><br><span class="line"><span class="string">+  if((prot &amp; PROT_READ) &amp;&amp; !f-&gt;readable)</span></span><br><span class="line"><span class="string">+    return -1;</span></span><br><span class="line"><span class="string">+  if((prot &amp; PROT_WRITE) &amp;&amp; (flags &amp; MAP_SHARED) &amp;&amp; !f-&gt;writable)</span></span><br><span class="line"><span class="string">+    return -1;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+  // alloc a vma</span></span><br><span class="line"><span class="string">+  struct VMA *vma = allocvma();</span></span><br><span class="line"><span class="string">+  if(!vma)  return -1;</span></span><br><span class="line"><span class="string">+  // fill in vma</span></span><br><span class="line"><span class="string">+  vma-&gt;perm = ((prot &amp; PROT_READ) ? PTE_R : 0) |</span></span><br><span class="line"><span class="string">+              ((prot &amp; PROT_WRITE) ? PTE_W : 0);</span></span><br><span class="line"><span class="string">+  vma-&gt;shared = (flags &amp; MAP_SHARED) ? 1 : 0;</span></span><br><span class="line"><span class="string">+  vma-&gt;filept = f;</span></span><br><span class="line"><span class="string">+  filedup(f);</span></span><br><span class="line"><span class="string">+  // add vma to process&#x27;</span>s linklist</span><br><span class="line">+  vma-&gt;nxt = p-&gt;vmalist;</span><br><span class="line">+  p-&gt;vmalist = vma;</span><br><span class="line">+  // find an unused region <span class="keyword">in</span> the process<span class="string">&#x27;s address space in which to map the file</span></span><br><span class="line"><span class="string">+  uint64 vmaddr = PGROUNDDOWN(p-&gt;curmax - length);</span></span><br><span class="line"><span class="string">+  if(vmaddr % PGSIZE != 0)  panic(&quot;sys_mmap&quot;);</span></span><br><span class="line"><span class="string">+  vma-&gt;vmstart = vmaddr;</span></span><br><span class="line"><span class="string">+  vma-&gt;vmend = p-&gt;curmax;</span></span><br><span class="line"><span class="string">+  p-&gt;curmax = vmaddr;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+  return vmaddr;</span></span><br><span class="line"><span class="string">+&#125;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+uint64</span></span><br><span class="line"><span class="string">+sys_munmap(void)</span></span><br><span class="line"><span class="string">+&#123;</span></span><br><span class="line"><span class="string">+  uint64 addr;</span></span><br><span class="line"><span class="string">+  int length;</span></span><br><span class="line"><span class="string">+  struct proc *p = myproc();</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+  if(argaddr(0, &amp;addr) &lt; 0 || argint(1, &amp;length) &lt; 0)</span></span><br><span class="line"><span class="string">+    return -1;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+  // find the VMA for the address range</span></span><br><span class="line"><span class="string">+  uint64 st = PGROUNDDOWN(addr);</span></span><br><span class="line"><span class="string">+  uint64 ed = PGROUNDUP(addr + length);</span></span><br><span class="line"><span class="string">+  struct VMA *vma = 0, *pre = 0;</span></span><br><span class="line"><span class="string">+  for(vma = p-&gt;vmalist; vma; vma = vma-&gt;nxt)&#123;</span></span><br><span class="line"><span class="string">+    if(vma-&gt;valid &amp;&amp; vma-&gt;vmstart &lt;= st &amp;&amp; ed &lt;= vma-&gt;vmend)</span></span><br><span class="line"><span class="string">+      break;</span></span><br><span class="line"><span class="string">+    pre = vma;</span></span><br><span class="line"><span class="string">+  &#125;</span></span><br><span class="line"><span class="string">+  if(!vma)  return -1;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+  // write back if needed</span></span><br><span class="line"><span class="string">+  if(vma-&gt;shared &amp;&amp; (vma-&gt;perm | PTE_W))</span></span><br><span class="line"><span class="string">+    mmapfilewrite(vma-&gt;filept, st, ed - st);</span></span><br><span class="line"><span class="string">+  // unmap specified pages</span></span><br><span class="line"><span class="string">+  for(uint64 i = st; i &lt; ed; i += PGSIZE)&#123;</span></span><br><span class="line"><span class="string">+    if(walkaddr(p-&gt;pagetable, i))&#123;</span></span><br><span class="line"><span class="string">+      // need to check because vma is allocated lazily</span></span><br><span class="line"><span class="string">+      uvmunmap(p-&gt;pagetable, i, 1, 1);</span></span><br><span class="line"><span class="string">+    &#125;</span></span><br><span class="line"><span class="string">+  &#125;</span></span><br><span class="line"><span class="string">+  // update info in vma</span></span><br><span class="line"><span class="string">+  if(vma-&gt;vmstart == st &amp;&amp; ed &lt; vma-&gt;vmend)</span></span><br><span class="line"><span class="string">+    vma-&gt;vmstart = PGROUNDDOWN(addr + length);</span></span><br><span class="line"><span class="string">+  else if(vma-&gt;vmstart &lt; st &amp;&amp; ed == vma-&gt;vmend)</span></span><br><span class="line"><span class="string">+    vma-&gt;vmend = PGROUNDUP(addr);</span></span><br><span class="line"><span class="string">+  else if(vma-&gt;vmstart == st &amp;&amp; ed == vma-&gt;vmend)&#123;</span></span><br><span class="line"><span class="string">+    if(pre == 0)  p-&gt;vmalist = vma-&gt;nxt;</span></span><br><span class="line"><span class="string">+    else  pre-&gt;nxt = vma-&gt;nxt, vma-&gt;nxt = 0;</span></span><br><span class="line"><span class="string">+    fileclose(vma-&gt;filept);</span></span><br><span class="line"><span class="string">+    deallocvma(vma);</span></span><br><span class="line"><span class="string">+  &#125;</span></span><br><span class="line"><span class="string">+  else ;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">+  return 0;</span></span><br><span class="line"><span class="string">+&#125;</span></span><br><span class="line"><span class="string">diff --git a/kernel/trap.c b/kernel/trap.c</span></span><br><span class="line"><span class="string">index a63249e..5afde8b 100644</span></span><br><span class="line"><span class="string">--- a/kernel/trap.c</span></span><br><span class="line"><span class="string">+++ b/kernel/trap.c</span></span><br><span class="line"><span class="string">@@ -68,11 +68,21 @@ usertrap(void)</span></span><br><span class="line"><span class="string">   &#125; else if((which_dev = devintr()) != 0)&#123;</span></span><br><span class="line"><span class="string">     // ok</span></span><br><span class="line"><span class="string">   &#125; else &#123;</span></span><br><span class="line"><span class="string">+  </span></span><br><span class="line"><span class="string">+    uint64 cause = r_scause();</span></span><br><span class="line"><span class="string">+    if(cause == 13 || cause == 15)&#123;</span></span><br><span class="line"><span class="string">+      // page fault</span></span><br><span class="line"><span class="string">+      uint64 stval = r_stval();</span></span><br><span class="line"><span class="string">+      if(mmaplazy(stval, cause) == 0)</span></span><br><span class="line"><span class="string">+        goto brk;</span></span><br><span class="line"><span class="string">+    &#125;</span></span><br><span class="line"><span class="string">+</span></span><br><span class="line"><span class="string">     printf(&quot;usertrap(): unexpected scause %p pid=%d\n&quot;, r_scause(), p-&gt;pid);</span></span><br><span class="line"><span class="string">     printf(&quot;            sepc=%p stval=%p\n&quot;, r_sepc(), r_stval());</span></span><br><span class="line"><span class="string">     p-&gt;killed = 1;</span></span><br><span class="line"><span class="string">   &#125;</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string">+brk:</span></span><br><span class="line"><span class="string">   if(p-&gt;killed)</span></span><br><span class="line"><span class="string">     exit(-1);</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string">diff --git a/time.txt b/time.txt</span></span><br><span class="line"><span class="string">new file mode 100644</span></span><br><span class="line"><span class="string">index 0000000..f599e28</span></span><br><span class="line"><span class="string">--- /dev/null</span></span><br><span class="line"><span class="string">+++ b/time.txt</span></span><br><span class="line"><span class="string">@@ -0,0 +1 @@</span></span><br><span class="line"><span class="string">+10</span></span><br><span class="line"><span class="string">diff --git a/user/user.h b/user/user.h</span></span><br><span class="line"><span class="string">index b71ecda..753b59a 100644</span></span><br><span class="line"><span class="string">--- a/user/user.h</span></span><br><span class="line"><span class="string">+++ b/user/user.h</span></span><br><span class="line"><span class="string">@@ -23,6 +23,8 @@ int getpid(void);</span></span><br><span class="line"><span class="string"> char* sbrk(int);</span></span><br><span class="line"><span class="string"> int sleep(int);</span></span><br><span class="line"><span class="string"> int uptime(void);</span></span><br><span class="line"><span class="string">+void *mmap(void *, int, int, int, int, int);</span></span><br><span class="line"><span class="string">+int munmap(void *, int);</span></span><br><span class="line"><span class="string"> </span></span><br><span class="line"><span class="string"> // ulib.c</span></span><br><span class="line"><span class="string"> int stat(const char*, struct stat*);</span></span><br><span class="line"><span class="string">diff --git a/user/usys.pl b/user/usys.pl</span></span><br><span class="line"><span class="string">index 01e426e..d23b9cc 100755</span></span><br><span class="line"><span class="string">--- a/user/usys.pl</span></span><br><span class="line"><span class="string">+++ b/user/usys.pl</span></span><br><span class="line"><span class="string">@@ -36,3 +36,5 @@ entry(&quot;getpid&quot;);</span></span><br><span class="line"><span class="string"> entry(&quot;sbrk&quot;);</span></span><br><span class="line"><span class="string"> entry(&quot;sleep&quot;);</span></span><br><span class="line"><span class="string"> entry(&quot;uptime&quot;);</span></span><br><span class="line"><span class="string">+entry(&quot;mmap&quot;);</span></span><br><span class="line"><span class="string">+entry(&quot;munmap&quot;);</span></span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io">kiloGrand</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io/2022/09/09/xv6-lab10/">https://kilogrand.gitee.io/2022/09/09/xv6-lab10/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kilogrand.gitee.io" target="_blank">kiloGrand</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/xv6/">xv6</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/09/08/xv6-lab9/"><img class="prev-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">xv6 实验九 file system</div></div></a></div><div class="next-post pull-right"><a href="/2022/09/10/xv6-lab11/"><img class="next-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">xv6 实验十一 networking</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/08/31/xv6-Chapter-0/" title="xv6 riscv book 中文版声明"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 riscv book 中文版声明</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-1/" title="xv6 第一章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第一章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-2/" title="xv6 第二章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第二章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-3/" title="xv6 第三章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第三章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-4/" title="xv6 第四章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第四章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-5/" title="xv6 第五章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第五章</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/profile.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">kiloGrand</div><div class="author-info__description">coder && data-science researcher</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/kiloGrand/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E6%AF%8F%E4%B8%AA%E8%BF%9B%E7%A8%8B%E7%9A%84VMA%EF%BC%88%E8%99%9A%E6%8B%9F%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F%EF%BC%89"><span class="toc-number">1.</span> <span class="toc-text">定义每个进程的VMA（虚拟内存区域）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#sys-mmap-%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.</span> <span class="toc-text">sys_mmap 的实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#munmap-%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.</span> <span class="toc-text">munmap 的实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#make-grade"><span class="toc-number">4.</span> <span class="toc-text">make grade</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#git-diff"><span class="toc-number">5.</span> <span class="toc-text">git diff</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理">自制深度学习框架--实现Yolov5的推理</a><time datetime="2023-03-24T12:00:00.000Z" title="发表于 2023-03-24 20:00:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理">自制深度学习框架--实现ResNet网络的推理</a><time datetime="2023-03-23T12:00:00.000Z" title="发表于 2023-03-23 20:00:00">2023-03-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程">自制深度学习框架--算子的执行流程</a><time datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系">自制深度学习框架--再探Tensor类并构建计算图的图关系</a><time datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现">自制深度学习框架--Im2Col原理与卷积层的实现</a><time datetime="2023-03-20T12:00:00.000Z" title="发表于 2023-03-20 20:00:00">2023-03-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By kiloGrand</div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>